package com.flyduck.security.config;

import com.flyduck.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * <p></p>
 *
 * @author flyduck 2021/7/2
 * @version V1.0
 * @modificationHistory=========================逻辑或功能性重大变更记录
 * @modify by user: flyduck 2021/7/2
 * @modify by reason:{方法名}:{原因}
 **/
@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests(item ->
                item.mvcMatchers("/home/**").permitAll()
                        .mvcMatchers("/user/**").hasRole("USER")//.anyRequest().denyAll()
        )
                .addFilter(new AppAuthenticationFilter(authenticationManager()))
                .addFilter(new AppAuthorizationFilter(authenticationManager()))
                .exceptionHandling().authenticationEntryPoint(new AppAuthenticationEntryPoint())
                .and().cors()
                .and()
                .csrf().disable();
    }
}
